import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import deadSitesData from '@/assets/data/deadSites.json'
import iconMapData from '@/assets/data/iconMap.json'

export const useCemeteryStore = defineStore('cemetery', () => {
  // 状态
  const deadSites = ref(deadSitesData)
  const iconMap = ref(iconMapData)
  const searchTerm = ref('')
  const currentFilter = ref('all') // all, website, app, service
  const currentRegion = ref('all') // all, domestic, international
  const currentCategory = ref('all') // all, 社交网络, 音乐流媒体, etc.
  const sortBy = ref('year') // year, name, category
  const sortOrder = ref('desc') // asc, desc
  const viewMode = ref('grid') // grid, timeline

  /**
   * 应用过滤条件到网站列表
   * @param {Array} sites - 要过滤的网站列表
   * @returns {Array} - 过滤后的网站列表
   */
  const applyFilters = (sites) => {
    if (!sites) return [];
    
    return sites.filter((site) => {
      // 应用搜索过滤
      const matchesSearch =
        !searchTerm.value ||
        site.name.toLowerCase().includes(searchTerm.value.toLowerCase()) ||
        site.description.toLowerCase().includes(searchTerm.value.toLowerCase()) ||
        (site.category && site.category.toLowerCase().includes(searchTerm.value.toLowerCase())) ||
        (site.url && site.url.toLowerCase().includes(searchTerm.value.toLowerCase()));

      // 应用类型过滤
      const matchesType =
        currentFilter.value === "all" || currentFilter.value === site.type;

      // 应用地区过滤
      const matchesRegion =
        currentRegion.value === "all" || currentRegion.value === site.region;

      // 应用分类过滤
      const matchesCategory =
        currentCategory.value === "all" ||
        currentCategory.value === site.category;

      return matchesSearch && matchesType && matchesRegion && matchesCategory;
    });
  };

  // 计算属性 - 过滤后的网站列表
  const filteredSites = computed(() => {
    const filtered = applyFilters(deadSites.value);
    
    // 排序
    filtered.sort((a, b) => {
      let aValue, bValue
      
      switch (sortBy.value) {
        case 'name':
          aValue = a.name.toLowerCase()
          bValue = b.name.toLowerCase()
          break
        case 'category':
          aValue = a.category
          bValue = b.category
          break
        case 'year':
        default:
          aValue = a.year
          bValue = b.year
          break
      }

      if (sortOrder.value === 'asc') {
        return aValue > bValue ? 1 : -1
      } else {
        return aValue < bValue ? 1 : -1
      }
    })

    return filtered
  })
  
  // 计算属性 - 过滤后的网站数量
  const filteredSitesCount = computed(() => {
    return filteredSites.value.length;
  });

  // 计算属性 - 按年份分组的网站
  const sitesByYear = computed(() => {
    const grouped = {}
    filteredSites.value.forEach(site => {
      if (!grouped[site.year]) {
        grouped[site.year] = []
      }
      grouped[site.year].push(site)
    })

    // 按年份排序
    const sortedYears = Object.keys(grouped).sort((a, b) => {
      return sortOrder.value === 'desc' ? b - a : a - b
    })

    const result = {}
    sortedYears.forEach(year => {
      result[year] = grouped[year]
    })

    return result
  })

  // 计算属性 - 统计数据
  const stats = computed(() => {
    const total = deadSites.value.length
    const domestic = deadSites.value.filter(site => site.region === 'domestic').length
    const international = deadSites.value.filter(site => site.region === 'international').length
    
    const byType = {
      website: deadSites.value.filter(site => site.type === 'website').length,
      app: deadSites.value.filter(site => site.type === 'app').length,
      service: deadSites.value.filter(site => site.type === 'service').length
    }

    const byCategory = {}
    deadSites.value.forEach(site => {
      byCategory[site.category] = (byCategory[site.category] || 0) + 1
    })

    const byYear = {}
    deadSites.value.forEach(site => {
      byYear[site.year] = (byYear[site.year] || 0) + 1
    })

    // 计算过滤后的数量，避免循环依赖
    const filteredCount = deadSites.value.filter(site => {
      const matchesSearch = !searchTerm.value || 
        site.name.toLowerCase().includes(searchTerm.value.toLowerCase()) ||
        site.description.toLowerCase().includes(searchTerm.value.toLowerCase())
      
      const matchesFilter = currentFilter.value === 'all' || site.type === currentFilter.value
      const matchesRegion = currentRegion.value === 'all' || site.region === currentRegion.value
      
      return matchesSearch && matchesFilter && matchesRegion
    }).length

    return {
      total,
      domestic,
      international,
      byType,
      byCategory,
      byYear,
      filtered: filteredCount
    }
  })

  // 计算属性 - 所有可用的分类
  const availableCategories = computed(() => {
    const categories = [...new Set(deadSites.value.map(site => site.category))]
    return categories.sort()
  })

  // 计算属性 - 所有可用的年份
  const availableYears = computed(() => {
    const years = [...new Set(deadSites.value.map(site => site.year))]
    return years.sort((a, b) => b - a)
  })

  // 方法 - 获取网站图标URL
  const getIconUrl = (name, url) => {
    // 如果有预定义的图标，使用它
    if (iconMap.value[name]) {
      return iconMap.value[name]
    }

    // 尝试使用 favicon 服务
    if (url && url !== 'N/A') {
      // 清理URL，确保格式正确
      const cleanUrl = url.replace(/^https?:\/\//, '').replace(/\/$/, '')
      return `https://www.google.com/s2/favicons?domain=${cleanUrl}&sz=32`
    }

    // 没有图标时返回null
    return null
  }

  // 方法 - 获取类型标签
  const getTypeLabel = (type) => {
    const labels = {
      website: '网站',
      app: '应用',
      service: '服务'
    }
    return labels[type] || type
  }

  // 方法 - 获取地区标签
  const getRegionLabel = (region) => {
    const labels = {
      domestic: '国内',
      international: '国外'
    }
    return labels[region] || region
  }

  // 方法 - 格式化日期
  const formatDate = (dateStr) => {
    const date = new Date(dateStr)
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    })
  }

  // 方法 - 重置所有过滤器
  const resetFilters = () => {
    searchTerm.value = ''
    currentFilter.value = 'all'
    currentRegion.value = 'all'
    currentCategory.value = 'all'
    sortBy.value = 'year'
    sortOrder.value = 'desc'
  }

  // 方法 - 设置搜索词
  const setSearchTerm = (term) => {
    searchTerm.value = term
  }

  // 方法 - 设置类型过滤器
  const setTypeFilter = (type) => {
    currentFilter.value = type
  }

  // 方法 - 设置地区过滤器
  const setRegionFilter = (region) => {
    currentRegion.value = region
  }

  // 方法 - 设置分类过滤器
  const setCategoryFilter = (category) => {
    currentCategory.value = category
  }

  // 方法 - 设置排序
  const setSorting = (field, order = 'desc') => {
    sortBy.value = field
    sortOrder.value = order
  }

  // 方法 - 切换排序顺序
  const toggleSortOrder = () => {
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
  }

  return {
    // 状态
    deadSites,
    iconMap,
    searchTerm,
    currentFilter,
    currentRegion,
    currentCategory,
    sortBy,
    sortOrder,
    viewMode,
    
    // 方法
    applyFilters,
    
    // 计算属性
    filteredSites,
    filteredSitesCount,
    sitesByYear,
    stats,
    availableCategories,
    availableYears,
    
    // 方法
    getIconUrl,
    getTypeLabel,
    getRegionLabel,
    formatDate,
    resetFilters,
    setSearchTerm,
    setTypeFilter,
    setRegionFilter,
    setCategoryFilter,
    setSorting,
    toggleSortOrder
  }
});
